package com.javaspeak.designpatterns.go4.behavioural.interpreter;

/**
 * Value is a wrapper that wraps values of different types and provides helper
 * methods to retrieve the types in different formats.  Note that attempting
 * to retrieve a value in the wrong format could result in an error.
 *
 * @author John Dickerson
 */
public class Value {

    private Object object;

    /**
     * Constructor
     *
     * @param object
     */
    public Value( Object object ){

        this.object = object;
    }


    /**
     * If the object is instance of String return it, else call toString()
     * method on it.  This method should not cause a ClassCastException if used
     * incorrectly.
     *
     * @return String value
     */
    public String getString(){

        if ( object instanceof String ){

            return ( String )object;
        }
        else {

            return object.toString();
        }
    }


    /**
     * This method will cast the object to Integer or attempt to convert the
     * value to an Integer.
     *
     * @return Integer
     */
    public Integer getInteger(){

        if ( object instanceof Integer ){

            return ( Integer )object;
        }
        else {

            // Note that if the object cannot be represented as an Integer
            // this could throw an error
            return new Integer( object.toString() );
        }
    }


    /**
     * Returns the object with no conversion
     *
     * @return object
     */
    public Object getObject(){

        return object;
    }


    public String toString(){

        if ( object instanceof String ){

            return getString();
        }
        else if ( object instanceof Integer ){

            return getInteger().toString();
        }
        else if ( object != null ){

            return object.toString();
        }
        else {

            return null;
        }
    }
}
